package com.wuxu.ads_no.domain.service

import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.AccessibilityServiceInfo
import android.accessibilityservice.GestureDescription
import android.accessibilityservice.GestureDescription.StrokeDescription
import android.graphics.Path
import android.os.Build
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo
import android.widget.Toast
import com.wuxu.ads_no.util.logD


/**
 *@author wuxu 21057340
 *@date 2024/1/26 3:27 PM
 *@description 使用无障碍服务跳过广告页
 */
class AdCheckService : AccessibilityService() {
    private val mTag = AdCheckService::class.java.simpleName
    override fun onAccessibilityEvent(event: AccessibilityEvent?) {
        "onAccessibilityEvent $event".logD(mTag)
        event?.apply{
           for(i in 0 until (source?.childCount?:1) ){
               val childNode = source?.getChild(i)
               "childNode:${childNode.toString()}".logD(mTag)
               childNode?.apply {
                   if (checkNodeIsNeed(this) ){
                       "找到符合要求的节点，$this".logD()
                      val result = clickNode(this)
                       if (!result){
                           "点击失败，尝试采用模拟位置点击".logD(mTag)
                           clickByPosition(this)
                       }else{
                           "点击成功!".logD(mTag)
                           Toast.makeText(this@AdCheckService,"跳过广告页！",Toast.LENGTH_SHORT).show()
                       }
                   }

               }
           }
        }
    }

    /**
     * 检查此节点是否符合要求
     */
    private fun checkNodeIsNeed(node: AccessibilityNodeInfo):Boolean{
        val txt = node.text?.toString()
        if (txt?.contains("跳过") == true|| txt?.contains("关闭") == true){//暂时先这样写，后面改为正则
            return true
        }
        return false
    }

    private fun clickNode(node: AccessibilityNodeInfo):Boolean{
      return  if (node.isClickable){
            node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
              true
        }else{
             node.parent?.let {
                return clickNode(node.parent)
             }?:false
        }
    }

    private fun clickByPosition(node: AccessibilityNodeInfo){
        //TODO ：1. 获取本地配置直接点击。2.1如果本地没有配置，尝试获取节点在屏幕中的位置，模拟点击
        dispatchGestureClick(913.8867F,173.22363F)
    }

    private fun dispatchGestureClick(x: Float, y: Float) {
        val path = Path()
        path.moveTo(x, y)
        val click = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//7.0 版本以下不支持模拟点击
            dispatchGesture(
                GestureDescription.Builder()
                    .addStroke(StrokeDescription(path, 0, 100)).build(), null, null
            )
        } else {
            false
        }
        "dispatchGestureClick: $click".logD(mTag)
    }


    override fun onInterrupt() {
    }

    override fun onServiceConnected() {
        super.onServiceConnected()
        "链接启动".logD()
    }


    /**
     * 代码动态设置无障碍服务配置信息
     * 这里是xml配置文件的延伸
     */
    private fun setServiceInfo(){
        serviceInfo = AccessibilityServiceInfo().apply {
            packageNames = arrayOf("")
        }
    }
}